<script lang="ts" setup>
import {reactive, ref, computed} from 'vue'
import {ElTable, ElMessage, ElMessageBox } from 'element-plus'
import {objectToString} from '@vue/shared'
import * as XLSX from 'xlsx'
// 在 script setup 顶部添加
import { onErrorCaptured } from 'vue';

onErrorCaptured((error) => {
  console.error('捕获到错误:', error);
  // 防止错误向上冒泡
  return false;
});


/**
 * 控制编辑对话框的显示与隐藏状态
 * 类型：Ref<boolean>
 */
const dialogVisible = ref(false)
const isEditing = ref(false)
const batchImportDialogVisible = ref(false)
const batchImportFile = ref(null)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)


/**
 * 员工表格数据集合，使用 reactive 包裹以实现响应式更新
 * 包含多个员工对象，每个对象具有以下字段：
 * - id: 员工唯一标识符（数字）
 * - name: 员工姓名（字符串）
 * - accountNumber: 系统账号（字符串）
 * - jobNumber: 工号（字符串）
 * - date: 到本单位日期（字符串格式的时间）
 * - section: 所在部门（字符串）
 * - status: 员工状态（如“试用”或“正式”，字符串）
 */
const tableData = reactive(
    [
      {
        id: 1,
        name: '小明',
        accountNumber: '1000011',
        jobNumber: '3188991',
        date: '2023-12-03 12:12:09',
        section: '技术部',
        status: '试用',
      },
      {
        id: 2,
        name: '小蔡',
        accountNumber: '1000012',
        jobNumber: '3188992',
        date: '2023-12-03 12:12:09',
        section: '销售部',
        status: '正式',
      },
      {
        id: 3,
        name: '小天',
        accountNumber: '1000013',
        jobNumber: '3188993',
        date: '2023-12-03 12:12:09',
        section: '财务部',
        status: '试用',
      },
      {
        id: 4,
        name: '小玉',
        accountNumber: '1000014',
        jobNumber: '3188994',
        date: '2023-12-03 12:12:09',
        section: '技术部',
        status: '正式',
      }
    ]
)
const formData = reactive({
  name: '',
  accountNumber: '',
  jobNumber: '',
  date: '',
  section: '',
  status: ''
})

const filterTableData = computed(() =>{
  if (!searchKeyword.value){
    return tableData
  }
  const keyword = searchKeyword.value.toLowerCase()
  return tableData.filter(employee =>
    employee.name.toLowerCase().includes(keyword) ||
    employee.jobNumber.toLowerCase().includes(keyword) ||
    employee.section.toLowerCase().includes(keyword)
  )
})
function handleSearch(){
  ElMessage.info('搜索关键词: ${searchKeyword.value}')
}

function handleSave() {
  ElMessage.success('保存成功')
  resetForm()
  // Object.assign(formData,{
  //   name: '',
  //   accountNumber: '',
  //   jobNumber: '',
  //   date: '',
  //   section: '',
  //   status: ''
  // })
  dialogVisible.value = false
}

function resetForm() {
  Object.assign(formData, {
    name: '',
    accountNumber: '',
    jobNumber: '',
    date: '',
    section: '',
    status: ''
  })
}

function editEmployee(employee) {
  Object.assign(formData, {
    name: employee.name,
    accountNumber: employee.accountNumber,
    jobNumber: employee.jobNumber,
    date: employee.date.split(' ')[0],
    section: employee.section,
    status: employee.status
  })
  isEditing.value = true
  dialogVisible.value = true
}

function deleteEmployee(employee) {
  //ElMessage.success('删除成功')
  const index = tableData.findIndex(item => item.id === employee.id)
  if (index !== -1) {
    tableData.splice(index, 1)
    ElMessage.success('删除成功')
  }
}
function openAddDialog() {
  dialogVisible.value = false
  resetForm()
  isEditing.value= false
  dialogVisible.value = true
}
function handleBatchImport() {
  //ElMessage.success('导入成功')
  batchImportDialogVisible.value = true
}
function handleBatchFileUpload() {
  // 这里应该实现实际的文件解析和导入逻辑
  batchImportDialogVisible.value = false
  batchImportFile.value?.submit();
  ElMessage.success('批量导入成功')
}
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}
function handleCurrentChange(val) {
  currentPage.value = val
}
function resetSearch() {
 searchKeyword.value=''
}
// 下载员工信息模板
function downloadEmployeeTemplate() {
  try {
    const templateData = [
      {
        '姓名': '',
        '系统账号': '',
        '工号': '',
        '到本单位日期': '',
        '所在部门': '',
        '员工状态': ''
      }
    ]

    const worksheet = XLSX.utils.json_to_sheet(templateData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '员工信息模板')

    // 使用 write 而不是 writeFile 来避免潜在的异步问题
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '员工信息模板.xlsx';
    link.click();
    URL.revokeObjectURL(url);
    //XLSX.writeFile(workbook, '员工信息模板.xlsx')
  }catch (error){
    console.error('下载模板失败:', error);
    ElMessage.error('下载模板失败');
  }
}

// 处理员工信息文件上传
// 定义 Excel 数据行的接口
interface EmployeeRow {
  '姓名': string;
  '系统账号': string;
  '工号': string;
  '到本单位日期': string;
  '所在部门': string;
  '员工状态': string;
  // 可选英文字段兼容
  name?: string;
  accountNumber?: string;
  jobNumber?: string;
  date?: string;
  section?: string;
  status?: string;
}

function handleEmployeeFileUpload(file) {
  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const result = e.target?.result;
      if (!(result instanceof ArrayBuffer)) {
        ElMessage.error('文件读取失败，数据格式不正确');
        return;
      }
      const data = new Uint8Array(result);
      const workbook = XLSX.read(data, { type: 'array' });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];

      // 明确指定泛型类型为 EmployeeRow
      const jsonData: EmployeeRow[] = XLSX.utils.sheet_to_json(worksheet);

      jsonData.forEach((item) => {
        const newRow = {
          id: tableData.length + 1,
          name: item['姓名'] || item.name || '',
          accountNumber: item['系统账号'] || item.accountNumber || '',
          jobNumber: item['工号'] || item.jobNumber || '',
          date: item['到本单位日期'] || item.date || '',
          section: item['所在部门'] || item.section || '',
          status: item['员工状态'] || item.status || ''
        };
        tableData.push(newRow);
      });

      batchImportDialogVisible.value = false;
      currentPage.value = 1;
      ElMessage.success('批量导入成功');
    } catch (error) {
      console.error('文件解析错误:', error);
      ElMessage.error('文件解析失败，请检查文件格式');
    }
  };
  reader.readAsArrayBuffer(file.raw);
}
// 分页后的数据
const paginatedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filterTableData.value.slice(start, end);
});

</script>

<!-- 员工信息主容器 -->
<template>
  <div class="container">
    <el-card shadow="always" class="main-card">
      <!-- 页面标题区域 -->
      <div class="header-section">
        <span class="page-title">员工信息</span>
      </div>
      <!-- 搜索功能区 -->
      <div class="search-section">
        <!-- 输入框和搜索按钮组合 -->
        <div class="search-input-wrapper">
          <el-input v-model="searchKeyword" placeholder="请输入姓名、工号或部门" class="mobile-full-width" @keyup.enter="handleSearch"/>
          <el-button type="primary"  @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch" class="action-button">重置</el-button>
        </div>
        <!-- 新增及批量导入操作按钮组 -->
        <div class="action-buttons">
          <el-button type="success" @click="openAddDialog" >新增</el-button>
          <el-button type="info"  @click="handleBatchImport" >批量导入</el-button>
        </div>
      </div>
      <!-- 表格展示区 -->
      <div class="table-wrapper">
        <el-table
            :data="paginatedTableData"
            border
            :header-cell-style="{ textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            class="employee-table responsive-table"
        >
          <!-- 序号列 -->
          <el-table-column prop="id" label="序号" min-width="60" show-overflow-tooltip/>
          <!-- 姓名列 -->
          <el-table-column prop="name" label="姓名" min-width="80"/>
          <!-- 系统账号列 -->
          <el-table-column prop="accountNumber" label="系统账号" min-width="100"/>
          <!-- 工号列 -->
          <el-table-column prop="jobNumber" label="工号" min-width="100"/>
          <!-- 到本单位日期列 -->
          <el-table-column prop="date" label="到本单位日期" min-width="140"/>
          <!-- 所在部门列 -->
          <el-table-column prop="section" label="所在部门" min-width="100"/>
          <!-- 员工状态列 -->
          <el-table-column prop="status" label="员工状态" min-width="80">
            <template #default="{ row }">
              <span class="status-tag" :class="row.status === '正式' ? 'status-active' : 'status-inactive'">
                {{ row.status }}
              </span>
            </template>
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column label="操作" fixed="right" width="160">
            <template #default="{ row }">
              <el-button type="primary" @click="editEmployee(row)" size="small">编辑</el-button>
              <el-button type="danger" @click="deleteEmployee(row)" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页控件区域 -->
      <div class="pagination-wrapper">
        <el-pagination
            size="small"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="filterTableData.length"
            :page-sizes="[10, 20, 50, 100]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="mt-4"
        />
      </div>
    </el-card>
    <!-- 编辑/新增员工信息弹窗 -->
    <el-dialog v-model="dialogVisible"  :title="isEditing ? '编辑员工信息' : '新增员工信息'" class="employee-dialog" @close="resetForm">
      <el-form label-width="110px" class="employee-form">
        <el-form-item label="姓名">
          <el-input v-model="formData.name"/>
        </el-form-item>
        <template v-if="isEditing">
          <el-form-item label="系统账号">
            <el-input v-model="formData.accountNumber" disabled/>
          </el-form-item>
          <el-form-item label="工号">
            <el-input v-model="formData.jobNumber" disabled/>
          </el-form-item>
        </template>
        <el-form-item label="到本单位日期">
          <el-date-picker v-model="formData.date" type="date" placeholder="选择日期" style="width: 100%;"
                          value-format="YYYY-MM-DD" format="YYYY-MM-DD"/>
        </el-form-item>
        <el-form-item label="所在部门">
          <el-select v-model="formData.section" placeholder="请选择" style="width: 100%;">
            <el-option label="技术部" value="技术部"/>
            <el-option label="销售部" value="销售部"/>
            <el-option label="财务部" value="财务部"/>
          </el-select>
        </el-form-item>
        <el-form-item label="员工状态" style="width: 100%">
          <el-select v-model="formData.status" placeholder="请选择" style="width: 100%;">
            <el-option label="正式" value="正式"/>
            <el-option label="试用" value="试用"/>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部按钮栏 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="!isEditing" @click="resetForm">重置</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

     <!-- 添加批量导入对话框 -->
    <el-dialog v-model="batchImportDialogVisible" title="批量导入员工信息" width="500px">
      <el-alert
          title="请按照模板格式准备数据，支持.xls和.xlsx格式文件"
          type="info"
          show-icon
          style="margin-bottom: 20px;"
          disabled
          :closable="false"
      />
      <el-upload
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleEmployeeFileUpload"
          accept=".xls,.xlsx"
          ref="batchImportFile"
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传Excel格式文件，确保包含员工信息字段
          </div>
        </template>
      </el-upload>
      <div class="import-actions">
        <el-link @click="downloadEmployeeTemplate" type="primary" >
          下载模板
        </el-link>
      </div>
      <div style="margin-top: 15px; font-size: 14px; color: #666;">
        <p><strong>导入说明：</strong></p>
        <p>1. 点击"下载模板"获取标准格式文件</p>
        <p>2. 按照模板格式填写员工信息</p>
        <p>3. 点击"选择文件"上传填写好的文件</p>
        <p>4. 系统将自动解析并导入数据</p>
      </div>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="batchImportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchFileUpload">确定导入</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header-section{
  margin-bottom: 20px;
}
.page-title{
  font-size: 20px;
  font-weight: bold;
}
</style>
